package com.yuntsg.ruiijn.controller.client;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.yuntsg.ruiijn.database.entity.WosBasic;
import com.yuntsg.ruiijn.database.mapper.WosBasicMapper;
import com.yuntsg.ruiijn.service.ManualCheckService;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import common.proxy.HttpUtil;
import common.util.FileUtils;
import common.util.PDFMERGE;
import common.util.StringUtil;
import common.util.XXTEA;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

import static com.yuntsg.ruiijn.service.AsyncService.localDateFilePath;

@RestController
@RequestMapping("client_upload")
@Slf4j
@SuppressWarnings("ALL")
//@Api(tags = "三方客户端接口")
public class ClientController {


    @Value("${upload.path}")
    public String uploadPath;
    @Resource
    ManualCheckService manualCheckService;
    @Autowired
    private WosBasicMapper wosBasicMapper;

    public synchronized static void convertTiffToJpg(String tiffFilePath, String jpgFilePath) throws IOException {

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 读取 TIF 图片
        System.out.println("输入文件_" + tiffFilePath);
        System.out.println("输出文件_" + jpgFilePath);

        BufferedImage tiffImage = ImageIO.read(new File(tiffFilePath));

        // 创建 JPG 图片文件
        File jpgFile = new File(jpgFilePath);

        // 将 TIF 图片写入 JPG 文件
        ImageIO.write(tiffImage, "PNG", jpgFile);
    }

    static BufferedImage ensureOpaque(BufferedImage bi) {
        if (bi.getTransparency() == BufferedImage.OPAQUE) {
            return bi;
        }
        int w = bi.getWidth();
        int h = bi.getHeight();
        int[] pixels = new int[w * h];
        bi.getRGB(0, 0, w, h, pixels, 0, w);
        BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        bi2.setRGB(0, 0, w, h, pixels, 0, w);
        return bi2;
    }

    /**
     * 查重客户端上串上来的数据全都走client
     *
     * @param file
     * @param gid
     * @return
     */
    @PostMapping("upload")
    public String uploadExcelAnsc(@RequestParam("file") MultipartFile file, @RequestParam("gid") Integer gid) {
        String cusPath = "client/" + gid + "/" + localDateFilePath();
        String saveFileName = ""; //1682737346688.PDF
        String finalFilePath = "";

        if (file != null) {
            FileUtils.existsFile(uploadPath + cusPath);///home/analysis/uploadFile/
            String fileRealName = file.getOriginalFilename();
            saveFileName = System.currentTimeMillis() + "___" + fileRealName;//1697765010507___1682737346688.PDF
            finalFilePath = uploadPath + cusPath + saveFileName;//  /home/analysis/uploadFile/  cilent/    231019/     1697765010507___1682737346688.PDF
            try {
                if (file.getOriginalFilename().endsWith("tif") || file.getOriginalFilename().endsWith("tiff")) {
                    System.out.println("检测到是 TIF 文件:" + finalFilePath);
                    file.transferTo(new File(finalFilePath));
                    saveFileName = saveFileName.replaceAll("-", "").replaceAll(" +", "").replaceAll("\\.tiff", "").replaceAll("\\.tif", "") + ".PNG";
                    convertTiffToJpg(finalFilePath, uploadPath + cusPath + saveFileName);
                } else {
                    file.transferTo(new File(finalFilePath));
                }
            } catch (IOException e) {
                uploadPath = "-1";
                System.out.println("图片转换异常");
                e.printStackTrace();
            }
        } else {
            System.out.println("文件是空的");
        }
        return cusPath + saveFileName;
    }

    /**
     * 查重系统上传的东西依旧放在查重系统目录下
     *
     * @param picPath 图片报告路径
     * @param txtPath 文字报告路径
     * @param wosId   wosId
     * @return
     */
    @GetMapping("upload_file")
    public ResultBean<Object> upload_file(String picPath, String txtPath, Integer wosId) {
        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
        wosBasic.setClientPicPath(picPath);//   20240621/  1697765010507___1682737346688.PDF
        wosBasic.setClientTxtPath(txtPath);
        wosBasicMapper.updateById(wosBasic);
        return new ResultBean<>("操作成功");
    }

    /**
     * 手动更新进度
     *
     * @param uuid 单篇文件的uuid
     * @param type 1图片报告 2文字报告
     * @return
     */
    @GetMapping("view_progress")
    public String view_progress(String uuid, Integer type) {
        WosBasic one = new LambdaQueryChainWrapper<>(wosBasicMapper).eq(WosBasic::getClientUuid, uuid).one();
        if (null != one) {
            if (type == 1) {
                String clientPicPath = one.getClientPicPath();
                if (StringUtil.isNotNull(clientPicPath)) {
                    return clientPicPath;
                }
            }
            if (type == 2) {
                String clientPicPath = one.getClientTxtPath();
                if (StringUtil.isNotNull(clientPicPath)) {
                    return clientPicPath;
                }
            }
        }
        return "暂无数据";
    }

    //    @ApiOperation(value = "02-本地文献模块,上传各类文件")
    @GetMapping("insert")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "path", value = "先调用上传接口 上传接口返回文件路径后当做参数带回到这里"),
//            @ApiImplicitParam(name = "content", value = "pmid/ut/doi"),
//            @ApiImplicitParam(name = "context", value = "自定义对比用的上传文本-gcr"),
//            @ApiImplicitParam(name = "author", value = "归属作者"),
//            @ApiImplicitParam(name = "title", value = "文章标题"),
//            @ApiImplicitParam(name = "fileType", value = "文件类型 1WOS_PDF 2 本地PDF 3 WORD 4 图片"),
//            @ApiImplicitParam(name = "splitType", value = "1 只要图片 2 只要文字 3 图文")
//    })
    public String insert(
            String realName,
            String phone,
            Integer gid,

            String path,
            String author,
            String title,

            Integer fileType,
            Integer splitType,

            String pmidDoi,
            String context

    ) {
        /**
         * 做假登录
         */
        Integer logid = 9900 + gid;
//        StpUtil.login(9900 + gid, 100);
        /**
         * 如果是多个PDF上传
         */
        if (fileType != null && fileType == 2) {//如果上传的是本地PDF文件
            if (path.contains("#P#D#F#")) {
                String pdfPath = localDateFilePath() + "MERGE_" + System.currentTimeMillis() + ".PDF";
                String[] paths = path.split("#P#D#F#");
                List<String> strings = Arrays.asList(paths);
                List<String> list = new ArrayList<>();
                for (String string : strings) {
                    list.add(uploadPath + string);
                }
                boolean succ = PDFMERGE.mergePdfFiles(list, uploadPath + pdfPath);
                if (succ) {
                    path = pdfPath;
                } else {
                    return "-1";
                }
            }
        }
        /**
         * 如果已经填写了PMID/DOI/UT 则需要给他们获取全文
         */
        String orgcontent = pmidDoi;
        if (null != pmidDoi) {
            boolean nextFlag = false;
            if (pmidDoi.contains("doi:") || pmidDoi.startsWith("10.") || pmidDoi.toLowerCase().startsWith("doi:")) {
                try {
                    pmidDoi = pmidDoi.toLowerCase().replaceAll("doi:", "").trim();
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("term", URLEncoder.encode(pmidDoi, "utf-8"));
                    String result = HttpRequest.post("http://165.140.240.249:808/pm-newsearch.php").header(Header.USER_AGENT, "Hutool http")//头信息，多个头信息多次调用此方法即可
                            .form(paramMap)//表单内容
                            .timeout(30000)//超时，毫秒
                            .execute().body();
                    JSONObject jsonObject = JSONUtil.parseObj(result);
                    if (jsonObject.get("type").equals(1)) {
                        JSONObject info = JSONUtil.parseObj(JSONUtil.parseArray(jsonObject.getStr("list")).get(0));
                        String pmid = info.getStr("pmid");
                        if (null != pmid) {
                            pmidDoi = pmid;
                            log.info("根据 DOI 获取到的 PMID 是___" + pmidDoi);
                        }
                    }
                } catch (Exception e) {
                }
            }
        }
        /**
         * 获取上传人
         */


        WosBasic wosBasic = new WosBasic();
        wosBasic.setUploadName(realName);
        wosBasic.setTxtComIds(null);
        wosBasic.setGid(gid);
        wosBasic.setAuthor(author);
        wosBasic.setMaster("委托");
        wosBasic.setMasterId(-1);
        wosBasic.setBelongDate(null);
        wosBasic.setDeptName("委托");
        wosBasic.setSelfTxt(0);
        wosBasic.setDeptId(1);
        wosBasic.setClientRealName(realName);
        wosBasic.setClientPhone(phone);
        log.info("额外处理获取ut号获取处理过之前的的pmid 是+" + orgcontent);
        //进行获取我的情况查询ut号码
        if (StringUtil.isNotNull(orgcontent)) {
            if (orgcontent.contains("doi:") || orgcontent.startsWith("10.")) {
                String getut = manualCheckService.getut(orgcontent);
                String getdoiTimeYear = manualCheckService.getdoiTimeYear(orgcontent);
                log.info("通过我的方法获取ut号是" + getut);
                log.info("通过我的方法获取发表时间是" + getdoiTimeYear);
                if (StringUtil.isNotNull(getut)) {
                    wosBasic.setCUt(getut);
                }
                if (StringUtil.isNotNull(getdoiTimeYear)) {
                    wosBasic.setCPy(getdoiTimeYear);
                }
            }
        }

        try {
            if (StringUtil.isNull(wosBasic.getCPm())) {
                if (pmidDoi.length() >= 7 && pmidDoi.length() <= 8) {
                    log.info("存入了pm+" + pmidDoi);
                    wosBasic.setCPm(pmidDoi);
                }
            }
            if (StringUtil.isNull(wosBasic.getCUt())) {
                if (pmidDoi.length() >= 14 && pmidDoi.length() <= 15) {
                    log.info("存入了ut+" + pmidDoi);
                    wosBasic.setCUt(pmidDoi);
                }
            }
            if (StringUtil.isNull(wosBasic.getCPy())) {
                Integer pmut = 2;
                if (pmidDoi.length() == 14 || pmidDoi.length() == 15) {
                    pmut = 1;
                }
                Integer selfArtYear = ManualCheckService.getpmutYear(pmidDoi, pmut);
                if (StringUtil.isNotNull(selfArtYear)) {
                    log.info("设置了年份selfArtYear" + selfArtYear);
                    wosBasic.setCPy(selfArtYear + "");
                }
            }
        } catch (Exception e) {
        }


        wosBasic.setFileType(fileType);
        wosBasic.setFilePath(path);//
        wosBasic.setPdfUrl(getPdf(pmidDoi));
        wosBasic.setCTi(title);
        wosBasic.setAnnex(null);//附件
        wosBasic.setSplit(1);//是否拆图
        wosBasic.setAdmCheck(1);
        wosBasic.setSplitType(splitType);
        wosBasic.setSimi("30");
        String clientUuid = UUID.fastUUID().toString();
        wosBasic.setClientUuid(clientUuid);
        wosBasicMapper.insert(wosBasic);


        long start1 = System.currentTimeMillis();
        WosBasic wosBasic1 = wosBasicMapper.selectById(wosBasic.getId());
        // 文字拆分放在这里
        if (splitType != null && splitType == 2) {
            wosBasic1.setSoType(3);

            log.info("没有传递默认传30相似度");
            wosBasic1.setSimi("30");

            Integer integer = 0;
            if (StringUtils.isEmpty(path)) {
                integer = manualCheckService.dealSinCheck(0, context, author, title, path, pmidDoi, logid);
            } else {
                integer = manualCheckService.dealSinCheck(2, context, author, title, path, pmidDoi, logid);
            }
            wosBasic1.setReFiD(integer);
            wosBasic1.setSplitAs(0);
        } else {
            if (splitType != null && splitType == 3) {
                log.info("前台走了下图文 进行文字拆分到表里面");
                Integer integer = 0;
                if (StringUtils.isEmpty(path)) {
                    integer = manualCheckService.dealSinCheck(0, context, author, title, path, pmidDoi, logid);
                } else {
                    integer = manualCheckService.dealSinCheck(2, context, author, title, path, pmidDoi, logid);
                }
                wosBasic1.setReFiD(integer);
                wosBasic1.setSplitAs(0);
            }
            wosBasic1.setSoType(2);
        }
        wosBasicMapper.updateById(wosBasic1);

//这里要返回uuid
        return "操作成功" + clientUuid;
    }

    /**
     * 获取全文路径
     *
     * @param content
     * @return
     */
    public static String getPdf(String content) {
        if (StringUtil.isEmpty(content)) {
            return null;
        }

        String abase64 = "";
        String newLink = "";
        String url = "";
        if (content.length() <= 8 && !content.startsWith("10.")) {
            abase64 = XXTEA.encryptToBase64StringNoSafe(content, "R0HWlCI3ndd1s8S3");
            url = "https://www.pubtsg.com/api/getpdfurl.do?unitid=1&type=0&query=" + abase64;
        } else {
            abase64 = XXTEA.encryptToBase64StringNoSafe(content.toUpperCase().replaceAll("WOS:", "").trim(), "R0HWlCI3ndd1s8S3");
            url = "https://www.pubtsg.com/api/getpdfurl.do?unitid=1&type=1&query=" + abase64;
        }
        BasicCookieStore cookieStore = new BasicCookieStore();
        String html = HttpUtil.postHtmlQuanWen(cookieStore, url, "", "");

        Map<String, Object> map = new HashMap<String, Object>();
        map = JSON.parseObject(html, Map.class);
        if (map.get("pdfurl") != null) {
            String pdfUrl = (String) map.get("pdfurl");
            return pdfUrl;
        }
        return null;
    }

}
